<template>
  <view class="share-type-container" :class="{ active: showShareType }">
    <view class="mask" @click="close"></view>
    <canvas canvas-id="myCanvas" :style="'width: '+width+'px; height: '+height+'px;'"></canvas>
    <view class="swiper-block">
      <slot></slot>
    </view>
    <view class="type-block">
      <view class="type-list">
        <view v-for="(item, index) in typeList" :key="index" class="type-item" @click="typeClick(item)">
          <image :src="typeImageObj[item.type]" mode="aspectFit" />
          <view>{{ item.text }}</view>
          <b-open-type v-if="item.type==='SHARE_APP_MESSAGE' || item.type==='SHARE_TIME_LINE'" open-type="share" />
        </view>
      </view>
      <view class="cancel" @click="close">关 闭</view>
    </view>
  </view>
</template>
<script>
import { mapState } from 'vuex'
import { setClipboardData } from '@/utils/tools'
import './index.scss'
export default {
  name: 'ShareType',
  props: {
    shareOption: {
      type: Object,
      default() {
        return {}
      }
    },
    canvasData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    width: {
      type: Number,
      default: 375
    },
    height: {
      type: Number,
      default: 667
    }
  },
  data() {
    return {
      showShareType: false,
      ctx: null,
      typeImageObj: {
        SHARE_TEXT: '/static/images/share/icon_share_01.png',
        SHARE_APP_MESSAGE: '/static/images/share/icon_share_04.png',
        SHARE_TIME_LINE: '/static/images/share/icon_share_02.png',
        SHARE_IMAGE: '/static/images/share/icon_share_03.png'
      },
      typeList: [],
      initFlag: false,
      shareImg: '',

      coupon_left: '',
      coupon_right: '',
      avatar: '',
      avatarWidth: 100,
      avatarHeight: 100,
      codeUrlImg: '',
      goodsImg: ''
    }
  },
  computed: {
    ...mapState([
      'userInfo'
    ])
  },
  created() {
    this.initTypeList()
  },
  methods: {
    initTypeList(option) {
      this.ctx = uni.createCanvasContext('myCanvas', this)

      // #ifdef MP-WEIXIN
      this.typeList = [
        { type: 'SHARE_TEXT', text: '复制文案' },
        { type: 'SHARE_APP_MESSAGE', text: '分享朋友' },
        { type: 'SHARE_IMAGE', text: '保存图文' }
      ]
      // #endif

      // #ifdef H5
      this.typeList = [
        { type: 'SHARE_TEXT', text: '复制文案' },
        { type: 'SHARE_IMAGE', text: '保存图文' }
      ]
      // #endif

      if (this.userInfo.head_img) {
        this.getImageInfo('avatar', this.userInfo.head_img)
      } else {
        this.avatar = '/static/images/mine/touxiang.png'
      }
      this.getImageInfo('coupon_left', 'https://asset-uat.bisinuolan.cn/bixuan_uni/images/biHuaSuan/coupon_left.png')
      this.getImageInfo('coupon_right', 'https://asset-uat.bisinuolan.cn/bixuan_uni/images/biHuaSuan/coupon_right.png')
    },
    show() {
      this.showShareType = true
    },
    close() {
      this.showShareType = false
    },
    getImageInfo(key, src, fn) {
      uni.getImageInfo({
        src,
        success: (res) => {
          if (key === 'avatar') {
            this.avatarWidth = res.width
            this.avatarHeight = res.height
          }
          this[key] = res.path
          if (fn) {
            fn()
          }
        },
        fail: (res) => {
          console.log(key, src, res)
        }
      })
    },
    typeClick(item) {
      switch (item.type) {
        case 'SHARE_TEXT':
          if (this.shareOption.share_text) {
            setClipboardData({
              data: this.shareOption.share_text,
              success: () => {
                uni.showToast({
                  title: '文案已复制成功',
                  icon: 'none',
                  duration: 1500
                })
                this.close()
              }
            })
          }
          break
        case 'SHARE_IMAGE':
          if (!this.codeUrlImg) {
            this.getImageInfo('codeUrlImg', this.canvasData.codeUrl, () => {
              this.getImageInfo('goodsImg', this.canvasData.goodsImage.pic, () => {
                this.generateImage()
              })
            })
          } else {
            this.getImageInfo('goodsImg', this.canvasData.goodsImage.pic, () => {
              this.generateImage()
            })
          }
          break
        default:
      }
    },
    getTextWidth(text, fontSize = 22) {
      this.ctx.font = `${fontSize}px sans-serif`
      return this.ctx.measureText(text).width
    },
    generateImage() {
      uni.showLoading({
        title: '海报生成中...'
      })
      const obj = this.canvasData
      let xPosition = 0

      // 背景
      this.ctx.rect(0, 0, this.width, this.height)
      this.ctx.setFillStyle('white')
      this.ctx.fill()

      // 昵称
      this.ctx.setFontSize(18)
      this.ctx.setFillStyle('#333')
      this.ctx.fillText(obj.nickname, 80, 38)

      // 描述
      this.ctx.setFontSize(14)
      this.ctx.setFillStyle('#909090')
      this.ctx.fillText('推荐一个好物，快来抢嘿！', 80, 58)

      // 商品图片
      this.ctx.drawImage(this.goodsImg, 10, 80, 355, 355)

      // 平台
      this.ctx.setFillStyle(obj.platform === 'PDD' ? 'red' : '#E1017E')
      this.ctx.fillRect(10, 445, 44, 18)
      this.ctx.setFontSize(12)
      this.ctx.setFillStyle('#FFF')
      this.ctx.fillText(obj.platformName, 14, 457)

      this.ctx.setFillStyle('#333')
      this.ctx.setFontSize(16)
      this.ctx.fillText(obj.title, 60, 460)

      xPosition = 10
      this.ctx.setFillStyle('#EA3644')
      this.ctx.setFontSize(18)
      this.ctx.fillText('￥' + obj.actualPrice, xPosition, 490)
      xPosition += (this.getTextWidth('￥' + obj.actualPrice, 18) + 4)
      this.ctx.setFontSize(12)
      if (this.canvasData.hasCoupon) {
        this.ctx.fillText('券后价', xPosition, 489)
        xPosition += (this.getTextWidth('券后价', 12) + 10)
      }

      this.ctx.setFillStyle('#909090')
      this.ctx.fillText('原价￥' + obj.originalPrice, xPosition, 490)
      if (obj.monthSales) {
        xPosition = this.getTextWidth('月销量' + obj.monthSales, 12) + 10
        this.ctx.fillText('月销量' + obj.monthSales, 375 - xPosition, 490)
      }

      if (obj.hasCoupon === 1) {
        // 优惠券背景
        this.ctx.drawImage(this.coupon_left, 5, 500, 250.5, 130)
        this.ctx.drawImage(this.coupon_right, 255, 500, 110, 130)

        this.ctx.setFillStyle('#FFF')
        this.ctx.setFontSize(18)
        xPosition = this.getTextWidth(obj.couponDiscount + '元优惠券', 18)
        this.ctx.fillText(obj.couponDiscount + '元优惠券', (252 - xPosition) / 2, 550)

        this.ctx.setFontSize(14)
        xPosition = this.getTextWidth(obj.couponUseStartTime + '~' + obj.couponUseEndTime, 14)
        this.ctx.fillText(obj.couponUseStartTime + '~' + obj.couponUseEndTime, (252 - xPosition) / 2, 580)

        // 二维码
        this.ctx.drawImage(this.codeUrlImg, 262.5, 513.5, 92, 92)
      } else {
        // 二维码
        this.ctx.drawImage(this.codeUrlImg, (375 - 92) / 2, 513.5, 92, 92)
        this.ctx.setFontSize(14)
        this.ctx.setFillStyle('#666')
        xPosition = this.getTextWidth('长按或扫码购买', 18)
        this.ctx.fillText('长按或扫码购买', (375 - xPosition) / 2, 630)
      }

      // 头像
      this.ctx.save()
      this.ctx.beginPath()
      this.ctx.arc(40, 40, 30, 0, 2 * Math.PI)
      this.ctx.setFillStyle('white')
      this.ctx.fill()
      this.ctx.clip()
      if (this.avatarWidth === this.avatarHeight) {
        this.ctx.drawImage(this.avatar, 10, 10, 60, 60)
      } else {
        const sx = (this.avatarWidth > this.avatarHeight) ? (this.avatarWidth - this.avatarHeight) / 2 : 0
        const sy = (this.avatarWidth > this.avatarHeight) ? 0 : (this.avatarHeight - this.avatarWidth) / 2
        const size = (this.avatarWidth > this.avatarHeight) ? this.avatarHeight : this.avatarWidth
        // console.log(this.avatarWidth, this.avatarHeight, sx, sy, size)
        this.ctx.drawImage(this.avatar, sx, sy, size, size, 10, 10, 60, 60)
      }
      this.ctx.stroke()
      this.ctx.restore()

      this.ctx.draw(false, () => {
        setTimeout(() => {
          uni.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: (res) => {
              this.shareImg = res.tempFilePath
              this.saveImage()
            },
            fail: (res) => {
              console.log(res)
              uni.hideLoading()
            }
          }, this)
        }, 800)
      })
    },
    saveImage() {
      // #ifdef H5
      uni.previewImage({
        current: this.shareImg,
        urls: [this.shareImg],
        success() {
          setTimeout(() => {
            uni.showToast({ title: '长按保存图片到相册再分享', icon: 'none', duration: 3000 })
          }, 500)
        }
      })
      // #endif

      // #ifdef MP-WEIXIN
      uni.saveImageToPhotosAlbum({
        filePath: this.shareImg,
        success: () => {
          uni.showToast({
            title: '保存成功',
            icon: 'none'
          })
          setTimeout(this.close, 300)
        },
        fail: (res) => {
          console.log(res)
          uni.hideLoading()
        }

      })
      // #endif
    }
  }
}
</script>

